<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <link
            rel="stylesheet"
            href="../bootstrap-3.4.1/bootstrap-3.4.1/dist/css/bootstrap.css"
        />
        <script src="../11.17/jquery-3.6.1.js"></script>
        <script src="../bootstrap-3.4.1/bootstrap-3.4.1/dist/js/bootstrap.js"></script>
        <script src="../city.js"></script>
        <style>
            body {
                /* display: flex; */
            }
            #box {
                margin: auto;
                margin-top: 30px;
                width: 1200px;
                height: 500px;
                overflow-y: auto !important;
            }
            td,
            th {
                text-align: center;
            }
            td {
                vertical-align: middle !important;
            }
            thead {
                background-color: rgba(0, 0, 0, 0.5);
                color: white;
                position: sticky;
                top: 0px;
            }

            /* select {
                width: 30% !important;
                display: inline-block !important;
            } */
            .mybtn {
                margin-left: 162px;
                margin-top: 20px;
            }
            .success-div {
                width: 40%;
                text-align: center;
                position: fixed;
                top: 40px;
                left: 33%;
                z-index: 999;
                display: none;
            }
            .form-inline {
                margin-left: 180px;
            }
            .sort-desc {
                cursor: pointer;
                color: blueviolet;
            }
        </style>
    </head>
    <body>
        <div>
            <button
                type="button"
                class="btn btn-primary btn-lg mybtn"
                data-toggle="modal"
                data-target="#myModal"
            >
                添加商品
            </button>
            <!-- Modal -->
            <div
                class="modal fade"
                id="myModal"
                tabindex="-1"
                role="dialog"
                aria-labelledby="myModalLabel"
            >
                <div class="alert alert-success success-div" role="alert">
                    商品添加成功
                </div>
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button
                                type="button"
                                class="close"
                                data-dismiss="modal"
                                aria-label="Close"
                            >
                                <span aria-hidden="true">&times;</span>
                            </button>
                            <h4 class="modal-title" id="myModalLabel">
                                添写商品表单
                            </h4>
                        </div>
                        <div class="modal-body">
                            <form class="form-group" id="goodsForm">
                                <div class="form-group has-feedback">
                                    <label>商品名称</label>
                                    <input
                                        type="text"
                                        class="form-control"
                                        name="goods_name"
                                        aria-describedby="商品名称输入正确"
                                    />
                                    <span
                                        class="glyphicon glyphicon-remove form-control-feedback"
                                        aria-hidden="true"
                                    ></span>
                                </div>
                                <div class="form-group">
                                    <label>价格</label>
                                    <input
                                        type="text"
                                        class="form-control"
                                        name="price"
                                    />
                                </div>
                                <div class="form-group">
                                    <label>库存</label>
                                    <input
                                        type="text"
                                        class="form-control"
                                        name="stock"
                                    />
                                </div>
                                <div class="form-group has-error has-feedback">
                                    <label>销量</label>
                                    <input
                                        type="text"
                                        class="form-control"
                                        name="sold"
                                    />
                                    <span
                                        class="glyphicon glyphicon-remove form-control-feedback"
                                        aria-hidden="true"
                                    ></span>
                                </div>
                                <div class="form-group">
                                    <label>商品图片</label>
                                    <input
                                        type="text"
                                        class="form-control"
                                        name="img"
                                        value="https://img12.360buyimg.com/n7/jfs/t1/185785/38/9092/69871/60c868cbE4edff8f2/ff55da132680832a.jpg"
                                    />
                                </div>
                                <div class="form-group">
                                    <label>状态</label>
                                    <label class="radio-inline">
                                        <input
                                            type="radio"
                                            name="status"
                                            value="1"
                                            checked
                                        />
                                        上架
                                    </label>
                                    <label class="radio-inline">
                                        <input
                                            type="radio"
                                            name="status"
                                            value="2"
                                        />
                                        下架
                                    </label>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button
                                type="button"
                                class="btn btn-default"
                                data-dismiss="modal"
                            >
                                关闭
                            </button>
                            <button
                                id="addGoods"
                                type="button"
                                class="btn btn-primary"
                            >
                                确定添加
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="form-inline">
                <label for="exampleInputEmail1">搜索商品</label>
                <input
                    type="search"
                    class="form-control"
                    id="keyword"
                    placeholder="输入商品名称"
                />
                <button id="btn" class="btn btn-default">搜索</button>
            </div>
        </div>
        <div id="box" class="table-responsive">
            <table class="table table-bordered table-hover">
                <thead>
                    <tr>
                        <th><input type="checkbox" id="all" /></th>
                        <th>ID</th>
                        <th>商品名称</th>
                        <th class="sort-desc">库存</th>
                        <th class="sort-desc">价格</th>
                        <th>状态</th>
                        <th class="sort-desc">销量</th>
                        <th>缩略图</th>
                        <th>创建时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
            <!-- -----------------------------三级联动----------------------------------------- -->

            <!-- <select class="form-control" id="province">
                <option value="">请选择省份</option>
            </select>
            <select class="form-control" id="city">
                <option>请选择市区</option>
            </select>
            <select class="form-control" id="area">
                <option>请选择区县</option>
            </select> -->
            <!-- ---------------------------全选反选------------------------------------------- -->
            <!-- <input type="checkbox" id="all" /> 全选
            <button class="btn btn-default" id="fan" />反选</button>
            <br />
            <input type="checkbox" name="childbox" />1 <input type="checkbox" name="childbox" />2
            <input type="checkbox" name="childbox"/>3 <input type="checkbox" name="childbox" />4
            <input type="checkbox" name="childbox"/>5 -->
        </div>
        <button
            style="margin-left: 180px; margin-top: 30px"
            id="del"
            class="btn btn-danger"
        >
            多选删除
        </button>
    </body>
    <style></style>
    <script>
        $(function () {
            showGoodsList()
            $('#addGoods').click(addGoodsFun)
            $('span[aria-hidden="true"]').hide()
            $('input[name="goods_name"]').keyup(checkParams)
            $('tbody').click(tbodyClickFun)
            //双击表格修改
            $('tbody').dblclick(EditClickFun)
            $('#all').change(allFun)
            $('#del').click(delCheckFun)
            $('#btn').click(searchFun)
            $('.sort-desc').click(sortFun)
        })
        var sort = {
            stock: 'asc',
            price: 'asc',
            sold: 'asc',
        }
        function sortFun() {
            let con = $(this).html()
            let thisType = null
            if (con == '库存') {
                sort.stock = sort.stock == 'asc' ? 'desc' : 'asc'
                thisType = 'stock'
            } else if (con == '价格') {
                sort.price = sort.price == 'asc' ? 'desc' : 'asc'
                thisType = 'price'
            } else {
                sort.sold = sort.sold == 'asc' ? 'desc' : 'asc'
                thisType = 'sold'
            }
            $.get(
                `https://liu.zzgoodqc.cn/goods/sort?sort=${sort[thisType]}&type=${thisType}`,
                function (res) {
                    if (res.code == 200) {
                        renderGoodsList(res.data)
                    }
                },
                'json'
            )
        }
        function searchFun() {
            let keyword = $('#keyword').val()
            if (!keyword) {
                showGoodsList()
                return false
            }
            $.ajax({
                url: 'https://liu.zzgoodqc.cn/goods/search',
                type: 'post',
                data: {
                    goods_name: keyword,
                },
                dataType: 'json',
                success: function (res) {
                    if (res.code == 200) {
                        renderGoodsList(res.data)
                    }
                },
            })
        }
        //双击编辑表格
        function EditClickFun() {
            //获取到双击的元素对象
            let thisObj = $(event.target)
            //判定是否符合编辑的td框
            if (thisObj[0].nodeName == 'TD' && thisObj.attr('name') == 'edit') {
                //把当前的td框的可编辑属性打开
                thisObj.attr('contenteditable', true)
                //获取焦点
                thisObj.focus()
            }
            //失去焦点时保存数据
            thisObj.blur(function () {
                //获取当前对象的父级的所有子级
                let obj = $(this).parent().children()
                let id = obj.eq(1).html()
                let name = obj.eq(2).html()
                let stock = obj.eq(3).html()
                let price = obj.eq(4).html()
                let status = obj.eq(5).html() == '上架' ? 1 : 2
                let sold = obj.eq(6).html()
                let img = obj.eq(7).children().attr('src')
                let data = {
                    id: id,
                    goods_name: name,
                    stock: stock,
                    price: price,
                    status: status,
                    sold: sold,
                    img: img,
                }
                $.post(
                    'https://liu.zzgoodqc.cn/goods/update',
                    data,
                    function (res) {
                        thisObj.attr('contenteditable', false)
                    },
                    'json'
                )
            })
        }
        function delCheckFun() {
            $('input:checked').each(function () {
                delGoodsById($(this).attr('data-id'), function () {
                    showGoodsList()
                })
            })
        }
        function allFun() {
            $('tbody input[type="checkbox"]').prop(
                'checked',
                $(this).prop('checked')
            )
        }
        function tbodyClickFun() {
            const delBtn = $(event.target)
            if (delBtn.html() == '删除') {
                let id = delBtn.attr('data-id')
                if (!confirm('确定要删除吗？')) {
                    return false
                }
                delGoodsById(id, function () {
                    delBtn.parent().parent().remove()
                })
            }
            if (delBtn.html().includes('架')) {
                let status = delBtn.html().includes('下') ? 2 : 1
                let id = delBtn.attr('data-id')
                $.get(
                    `https://liu.zzgoodqc.cn/goods/updateStatus?id=${id}&status=${status}`,
                    function (res) {
                        if (res.code == 200) {
                            delBtn.html(status == 1 ? '下架' : '上架')
                            delBtn
                                .parent()
                                .parent()
                                .children()
                                .eq(5)
                                .html(status == 1 ? '上架' : '下架')
                        }
                    },
                    'json'
                )
            }
        }
        function delGoodsById(id, callback) {
            $.get(
                'https://liu.zzgoodqc.cn/goods/delete?id=' + id,
                function (res) {
                    if (res.code == 200) {
                        callback(true)
                    }
                },
                'json'
            )
        }
        //添加商品
        function addGoodsFun() {
            let formData = $('#goodsForm').serializeArray()
            let data = {}
            formData.forEach((item) => {
                data[item.name] = item.value
            })
            if (!checkParams(data)) {
                return false
            }
            $.post(
                'https://liu.zzgoodqc.cn/goods/add',
                data,
                function (res) {
                    if (res.code == 200) {
                        $('.success-div').show('100', function () {
                            showGoodsList()
                            setTimeout(function () {
                                $('.success-div').hide()
                                $('#myModal').modal('toggle')
                            }, 2000)
                        })
                    }
                },
                'json'
            )
            console.log(data)
        }
        function checkParams() {
            if (!$('input[name="goods_name"]').val()) {
                $('input[name="goods_name"]')
                    .focus()
                    .next()
                    .removeClass('glyphicon-ok')
                    .addClass('glyphicon-remove')
                    .show()
                    .parent()
                    .removeClass('has-success')
                    .addClass('has-error')
            } else {
                $('input[name="goods_name"]')
                    .focus()
                    .next()
                    .removeClass('glyphicon-remove')
                    .addClass('glyphicon-ok')
                    .show()
                    .parent()
                    .removeClass('has-error')
                    .addClass('has-success')
            }
            return true
        }
        //显示商品列表
        function showGoodsList() {
            $.get(
                'https://liu.zzgoodqc.cn/goods/goodslist',
                function (res) {
                    console.log(res)
                    if (res.code == 200) {
                        renderGoodsList(res.data)
                    }
                },
                'json'
            )
        }
        //渲染商品列表
        function renderGoodsList(data) {
            // data.sort((a, b) => {
            //     return b.id - a.id
            // })
            let html = ''
            data.forEach((item, index) => {
                html += `<tr >
                            <td><input type="checkbox" data-id='${
                                item.id
                            }' /></td>
                            <td>${item.id}</td>
                            <td name='edit'>${item.goods_name}</td>
                            <td name='edit'>${item.stock}</td>
                            <td name='edit'>${item.price}</td>
                            <td>${item.status == 1 ? '上架' : '下架'}</td>
                            <td name='edit'>${item.sold}</td>
                            <td>
                                <img  class="img-thumbnail" src="${
                                    item.img
                                }" alt="" width="100" />
                            </td>
                            <td>${getDate(item.created_at)}</td>
                            <td>
                                <button data-id='${
                                    item.id
                                }' class="btn btn-info">${
                    item.status == '1' ? '下架' : '上架'
                }</button>
                                <button class="btn btn-danger del" data-id='${
                                    item.id
                                }'>删除</button>
                                <button class="btn btn-info">编辑</button>
                            </td>
                        </tr>`
            })
            $('tbody').html(html)
        }
        function getDate(n) {
            let date = new Date(n)
            let year = date.getFullYear()
            let month = date.getMonth() + 1
            let day = date.getDate()
            let hour = date.getHours()
            let minute = date.getMinutes()
            let second = date.getSeconds()
            return `${year}-${month}-${day} ${hour}:${minute}:${second}`
        }
        // ----------------------------三级联动----------------------------------------------
        // var pIndex = 0
        // $(function () {
        //     showProvince()
        //     $('#province').change(function () {
        //         let index = $(this).val()
        //         pIndex = index
        //         showCity()
        //     })
        //     $('#city').change(function () {
        //         let index = $(this).val() //获取当前选中的城市的索引
        //         showArea(index)
        //     })
        // })

        // function showProvince() {
        //     let html = '<option value="">请选择省份</option>'
        //     citys.forEach((item, index) => {
        //         html += `<option value="${index}">${item.name}</option>`
        //     })
        //     $('#province').html(html)
        // }
        // function showCity() {
        //     $('#area').html('<option>请选择区县</option>')
        //     let data = citys[pIndex].city
        //     let html = '<option value="">请选择区市</option>'
        //     data.forEach((item, areaIndex) => {
        //         html += `<option value="${areaIndex}" >${item.name}</option>`
        //     })
        //     $('#city').html(html)
        // }
        // function showArea(cIndex) {
        //     console.log(cIndex, pIndex)
        //     let data = citys[pIndex].city[cIndex].area
        //     let html = '  <option>请选择区县</option>'
        //     data.forEach((item, index) => {
        //         html += `<option value="${index}">${item}</option>`
        //     })
        //     $('#area').html(html)
        // }
        // --------------------------------------全选反选------------------------------------
        // $(function(){
        //     $('#all').change(function(){
        //         $('input[name="childbox"]').prop('checked', $(this).prop('checked'));
        //     })
        //     $('input[name="childbox"]').change(checkFun)
        //     $('#fan').click(function(){
        //         $('input[name="childbox"]').each(function(){
        //             $(this).prop('checked', !$(this).prop('checked'));
        //         })
        //         checkFun()
        //     })
        // })
        // function checkFun(){
        //         $('#all').prop('checked', $('input[name="childbox"]:checked').length == $('input[name="childbox"]').length);
        // }
        // --------------------------------递归数组------------------------------------------
        // var nums = [
        //     1,
        //     2,
        //     [3, 4, [5, [2, 9], [8, 0, [6, [7, [12], 6], 5], 1], 1], 5],
        //     123,
        // ]
        // //使用递归的方式将数组中的所有数字都打印出来
        // //闭包 递归
        // function fun() {
        //     let tmp = []
        //     function n(arr) {
        //         arr.forEach((item) => {
        //             if (Array.isArray(item)) {
        //                 n(item)
        //             } else {
        //                 tmp.push(item)
        //             }
        //         })
        //         return tmp
        //     }
        //     return n
        // }
        // let n = fun()
        // let res = n(nums)
        // console.log(res)
    </script>
</html>
